'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Layout from '../components/Layout';
import { useAuth } from '../contexts/AuthContext';
import {
  IconUser,
  IconScale,
  IconRuler,
  IconCalendar,
  IconTarget,
  IconChartBar,
  IconClipboardList,
  IconHeartbeat,
  IconPencil,
  IconLoader2
} from '@tabler/icons-react';

interface UserProfile {
  name: string | null;
  email: string;
  age: number | null;
  gender: string | null;
  height: number | null;
  weight: number | null;
  healthGoal: string | null;
}

interface Stats {
  totalRecords: number;
  daysTracked: number;
  averageCalories: number;
  latestWeight: number | null;
}

export default function Profile() {
  const { user, loading: authLoading } = useAuth();
  const router = useRouter();
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [stats, setStats] = useState<Stats | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!authLoading && !user) {
      router.push('/login?redirect=/profile');
      return;
    }

    if (user) {
      Promise.all([
        // 获取用户详细信息
        fetch('/api/user/profile', { credentials: 'include' })
          .then(res => res.json())
          .then(data => setProfile(data.profile)),

        // 获取用户统计数据
        fetch('/api/user/stats', { credentials: 'include' })
          .then(res => res.json())
          .then(data => setStats(data.stats))
      ]).finally(() => setLoading(false));
    }
  }, [user, authLoading, router]);

  const getHealthGoalText = (goal: string | null | undefined): string => {
    const goals: { [key: string]: string } = {
      'weight_loss': '减重',
      'muscle_gain': '增肌',
      'maintenance': '保持健康',
      'better_diet': '改善饮食习惯'
    };
    return goals[goal || ''] || '未设置';
  };

  const getGenderText = (gender: string | null | undefined): string => {
    const genders: { [key: string]: string } = {
      'male': '男',
      'female': '女',
      'other': '其他'
    };
    return genders[gender || ''] || '未设置';
  };

  if (loading) {
    return (
      <Layout>
        <div className="flex justify-center items-center min-h-[60vh]">
          <IconLoader2 className="w-6 h-6 animate-spin text-blue-600" />
        </div>
      </Layout>
    );
  }

  return (
    <Layout>
      <div className="max-w-6xl mx-auto">
        <div className="bg-white p-8">
          <div className="flex justify-between items-center mb-8">
            <h1 className="text-2xl font-bold">个人中心</h1>
            <button
              onClick={() => router.push('/profile/edit')}
              className="btn-primary flex items-center gap-2"
            >
              <IconPencil className="w-5 h-5" />
              编辑资料
            </button>
          </div>

          <div className="grid md:grid-cols-2 gap-8">
            {/* 个人信息卡片 */}
            <div className="space-y-6">
              <div className="bg-gray-50 rounded-lg p-6">
                <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
                  <IconUser className="w-5 h-5 text-blue-600" />
                  基本信息
                </h2>
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-gray-600">邮箱</span>
                    <span className="font-medium">{profile?.email}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-gray-600">姓名</span>
                    <span className="font-medium">{profile?.name || '未设置'}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-gray-600">性别</span>
                    <span className="font-medium">{getGenderText(profile?.gender)}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-gray-600">年龄</span>
                    <span className="font-medium">{profile?.age ? `${profile.age}岁` : '未设置'}</span>
                  </div>
                </div>
              </div>

              <div className="bg-gray-50 rounded-lg p-6">
                <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
                  <IconScale className="w-5 h-5 text-green-600" />
                  身体数据
                </h2>
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-gray-600">身高</span>
                    <span className="font-medium">{profile?.height ? `${profile.height}cm` : '未设置'}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-gray-600">体重</span>
                    <span className="font-medium">{profile?.weight ? `${profile.weight}kg` : '未设置'}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-gray-600">健康目标</span>
                    <span className="font-medium">{getHealthGoalText(profile?.healthGoal)}</span>
                  </div>
                </div>
              </div>
            </div>

            {/* 统计数据和快捷功能 */}
            <div className="space-y-6">
              {/* 统计数据 */}
              <div className="bg-gray-50 rounded-lg p-6">
                <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
                  <IconChartBar className="w-5 h-5 text-blue-600" />
                  数据统计
                </h2>
                <div className="grid grid-cols-2 gap-4">
                  <div className="bg-white rounded-lg p-4 text-center">
                    <div className="text-gray-600 text-sm mb-1">记录天数</div>
                    <div className="text-2xl font-bold text-blue-600">{stats?.daysTracked || 0}</div>
                  </div>
                  <div className="bg-white rounded-lg p-4 text-center">
                    <div className="text-gray-600 text-sm mb-1">记录总数</div>
                    <div className="text-2xl font-bold text-green-600">{stats?.totalRecords || 0}</div>
                  </div>
                  <div className="bg-white rounded-lg p-4 text-center">
                    <div className="text-gray-600 text-sm mb-1">平均热量</div>
                    <div className="text-2xl font-bold text-orange-600">
                      {stats?.averageCalories ? Math.round(stats.averageCalories) : 0}
                      <span className="text-sm ml-1">kcal</span>
                    </div>
                  </div>
                  <div className="bg-white rounded-lg p-4 text-center">
                    <div className="text-gray-600 text-sm mb-1">最新体重</div>
                    <div className="text-2xl font-bold text-purple-600">
                      {stats?.latestWeight ? `${stats.latestWeight}kg` : '未记录'}
                    </div>
                  </div>
                </div>
              </div>

              {/* 快捷功能 */}
              <div className="bg-gray-50 rounded-lg p-6">
                <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
                  <IconTarget className="w-5 h-5 text-purple-600" />
                  快捷功能
                </h2>
                <div className="grid gap-3">
                  <button
                    onClick={() => router.push('/diet-recommend')}
                    className="w-full bg-white hover:bg-gray-50 p-4 rounded-lg text-left flex items-center gap-3"
                  >
                    <IconHeartbeat className="w-5 h-5 text-red-500" />
                    <span>获取饮食推荐</span>
                  </button>
                  <button
                    onClick={() => router.push('/diet-record/add')}
                    className="w-full bg-white hover:bg-gray-50 p-4 rounded-lg text-left flex items-center gap-3"
                  >
                    <IconClipboardList className="w-5 h-5 text-green-500" />
                    <span>记录今日饮食</span>
                  </button>
                  <button
                    onClick={() => router.push('/health-advice')}
                    className="w-full bg-white hover:bg-gray-50 p-4 rounded-lg text-left flex items-center gap-3"
                  >
                    <IconTarget className="w-5 h-5 text-blue-500" />
                    <span>查看健康建议</span>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Layout>
  );
} 